package com.card.manager.services.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.card.framework.mybatis.mapper.BatchCallBack;
import com.card.framework.mybatis.mapper.MyFrameworkSupperMapper;
import com.card.framework.mybatis.optimist.ModifiedByAnotherUserException;
import com.card.framework.page.model.PageModel;
import com.card.manager.dao.UsersMapper;
import com.card.manager.dao.UsersRolesMapper;
import com.card.manager.domain.Roles;
import com.card.manager.domain.Users;
import com.card.manager.domain.UsersExample;
import com.card.manager.domain.UsersExample.Criteria;
import com.card.manager.domain.UsersRoles;
import com.card.manager.domain.UsersRolesExample;
import com.card.manager.services.UserService;

@Service("UserServiceImpl")
public class UserServiceImpl extends MyFrameworkSupperMapper implements UserService{

	@Override
	public int findUser(String username, String password , String dbKey) {
		final UsersMapper useMapper = getMapper(UsersMapper.class);
		UsersExample userExample = new UsersExample();
		userExample.createCriteria().andUsernameEqualTo(username);
		List<Users> result= (List<Users>)useMapper.selectByExample(userExample);
		Users bean = null;
		if(result!=null && result.size()>0){
			bean = result.get(0);
		}
		if (bean == null){
			return 2;
		}else if(bean.getDbkey()==null||!bean.getDbkey().equals(dbKey)){
			return 3;
		}else if(bean.getPassword().equals(password)){
			return 1;
		}else{
			return 0;
		}
	}

	@Override
	@Transactional
	public void updateUser(Users user) {
		UsersMapper mapper = this.getMapper(UsersMapper.class);
		mapper.updateByPrimaryKey(user);
		UsersRolesMapper urMapper = this.getMapper(UsersRolesMapper.class);
		UsersRolesExample example = new UsersRolesExample();
		example.createCriteria().andUseridEqualTo(user.getUserid());
		urMapper.deleteByExample(example);
		if(user.getRoles() != null && user.getRoles().size() > 0){
			for(Roles role : user.getRoles()){
				UsersRoles ur = new UsersRoles();
				ur.setUserid(user.getUserid());
				ur.setRoleid(role.getRoleid());
				urMapper.insert(ur);
			}
		}
	}

	@Override
	public void deleteUser(Long id) {
		// TODO Auto-generated method stub
		
	}

	@Override
	@Transactional
	public void insertUser(Users user) {
		UsersMapper mapper = this.getMapper(UsersMapper.class);
		mapper.insert(user);
	}
	
	@Override
	public int updatePassword(String username, String opass, String npass) {
		final UsersMapper useMapper = getMapper(UsersMapper.class);
		UsersExample userExample = new UsersExample();
		userExample.createCriteria()
			.andUsernameEqualTo(username)
			.andPasswordEqualTo(opass);
		List<Users> result= (List<Users>)useMapper.selectByExample(userExample);
		if(result == null || result.size() == 0){
			return 0;
		}else{
			Users user = result.get(0);
			user.setPassword(npass);
			useMapper.updateByPrimaryKey(user);
			return 1;
		}
	}

	@Override
	public Map<String, Object> selectUserForPage(String currUsername,Users user, PageModel pageModel) {
		UsersMapper mapper = this.getMapper(UsersMapper.class);
		UsersExample example = new UsersExample();
		if(pageModel != null)
			example.setPage(pageModel);
		if(StringUtils.isNotEmpty(pageModel.getSort())) 
			example.setOrderByClause(pageModel.getSort()+" "+pageModel.getOrder());
		Criteria criteria  = example.createCriteria();
		if(StringUtils.isNotBlank(user.getUsername()))
			criteria.andUsernameLike("%" + user.getUsername() + "%");
		if(StringUtils.isNotBlank(user.getName()))
			criteria.andNameLike("%" + user.getName() + "%");
		criteria.andUsernameNotEqualTo(currUsername);
		criteria.andDelflgEqualTo((byte)1);
		criteria.andUseridGreaterThanOrEqualTo(0);
		List<Users> list = mapper.selectByExample(example);
		Map<String, Object> modelMap = new HashMap<String, Object>();  
	    modelMap.put("total", pageModel.getTotalCount());  
	    modelMap.put("rows", list); 
	    return modelMap;
	}

	@Override
	public Users getById(int id) {
		UsersMapper mapper = this.getMapper(UsersMapper.class);
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	@Transactional
	public void deleteUsers(final List<Users> users) 
			throws ModifiedByAnotherUserException, Exception{
		batchSubmit(UsersMapper.class,new BatchCallBack() {
			@Override
			public <E> void batchCallBack(E mapper) {
				if(users != null && users.size() > 0) {
					for(Users a :users){
						a.setDelflg((byte)0);
						((UsersMapper) mapper).updateByPrimaryKeySelective(a);
					}
				}
			}
		});
	}

	@Override
	public boolean isExistUsername(String username) {
		UsersMapper userMapper = this.getMapper(UsersMapper.class);
		UsersExample userExample = new UsersExample();
		userExample.createCriteria().andUsernameEqualTo(username);
		List<Users> list = userMapper.selectByExample(userExample);
		if(list == null || list.size() == 0)
			return false;
		else 
			return true;
	}

	@Override
	@Transactional
	public void insertRoles(int userid, Set<Roles> roles) {
		if(roles != null && roles.size() > 0){
			UsersRolesMapper urMapper = this.getMapper(UsersRolesMapper.class);
			for(Roles role : roles){
				UsersRoles ur = new UsersRoles();
				ur.setUserid(userid);
				ur.setRoleid(role.getRoleid());
				urMapper.insert(ur);
			}
		}
	}

}
